package com.xingfei.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.constants.GeneralConstants;
import com.xingfei.blog.service.WebUserInfoService;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.*;
import com.xingfei.blog.vo.UserInfoVO;
import com.xingfei.blog.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by xingfei on 2017/1/16.
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private WebUserInfoService webUserInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/findUserById/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public UserVO findUserByuserId(@PathVariable Long userId) {
        UserVO userVo = this.webUserService.findUserByUserId(userId);
        return userVo;
    }

    /**
     * 获取用户详细信息
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/findUserInfoById/{userId}", method = RequestMethod.GET)
    public UserInfoVO findUserInfoById(@PathVariable Long userId) {
        UserInfoVO userInfoVO = this.webUserInfoService.getUserInfoByUserId(userId);
        if (userInfoVO == null) {
            userInfoVO = new UserInfoVO();
            userInfoVO.setAddress("测试测试测试测试自定义mapper");
        }
        return userInfoVO;
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request,HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>1){
            try {
                Cookie cookie2 = CookieUtil.getCookie(request, "token");
                if(cookie2!=null){
                    String token = cookie2.getValue();
                    if(StringUtils.isNotEmpty(token)){
                        if(request.getSession().getAttribute(token)!=null) {
                            request.getRequestDispatcher("/user/success").forward(request, response);
                        }else {
                            //删除浏览器cookie
                            Cookie cookie = CookieUtil.getCookie(request, "token");
                            CookieUtil.removeCookie(response,cookie);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "/login";
    }

    /**
     * 用户注册
     *
     * @param email    注册邮箱
     * @param password 密码
     * @param imgCode  图片验证码
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public JsonResult register(HttpServletRequest request, HttpServletResponse response
            , String email
            , String password
            , String phone
            , String imgCode) {

        JsonResult jsonResult = null;
        //校验验证码
        if (StringUtils.isNotEmpty(imgCode)) {
            //手机注册
            if(org.apache.commons.lang3.StringUtils.isNotBlank(phone)){
                //校验验证码
                String messageCode = stringRedisTemplate.opsForValue().get(phone);
                //校验手机号
                if(ValidateUtil.isMobileNO(phone)){
                    if(imgCode.compareToIgnoreCase(messageCode)==0){
                        //调用service添加数据
                        jsonResult = getJsonResult(email, password, phone, jsonResult);
                    }else{
                        jsonResult = new JsonResult(false, ErrorConstants.CHECK_CODE_ERROR, "验证码输入错误");
                    }
                }else{
                    jsonResult = new JsonResult(false, ErrorConstants.PHONE_ERROR, "手机号不合法");
                }
            }
            //邮箱注册
            else{
                HttpSession session = request.getSession();
                String sessionImgCode = (String) session.getAttribute("blog-xingfei-imgcode");
                //移除session
                session.removeAttribute("blog-xingfei-imgcode");
                if (StringUtils.isNotEmpty(imgCode) && StringUtils.isNotEmpty(sessionImgCode) && imgCode.compareToIgnoreCase(sessionImgCode)==0) {
                    //校验用户名密码合法性
                    if (StringUtils.isNotEmpty(email) && StringUtils.isNotEmpty(password)) {
                        //校验邮箱格式
                        if (ValidateUtil.checkEmail(email)) {
                            //调用service添加数据
                            jsonResult = getJsonResult(email, password, phone, jsonResult);

                        } else {
                            //返回错误结果集
                            jsonResult = new JsonResult(false, ErrorConstants.EMAIL_ERROR, "邮箱格式错误");
                        }
                    }
                } else {
                    jsonResult = new JsonResult(false, ErrorConstants.CHECK_CODE_ERROR, "验证码输入错误");
                }
            }
        }else{
            jsonResult = new JsonResult(false, ErrorConstants.CHECK_CODE_ERROR, "验证码输入错误");
        }
        return jsonResult;
    }

    private JsonResult getJsonResult(String email, String password, String phone, JsonResult jsonResult) {
        //加密密码
        try {
            password = MD5Util.getMD5(DESUtil.decryption(password, GeneralConstants.DES_DECODE_KEY));
            Integer result = this.webUserService.saveUser(phone, email, password);
            if (result > 0) {
                //返回错误结果集
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_SUCCESS, "注册成功");
            }
        } catch (Exception e) {
            //返回错误结果集
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
        }
        return jsonResult;
    }

    /**
     * login登陆验证
     */
    /*@RequestMapping(value = "/login",method = RequestMethod.POST)
    public @ResponseBody JsonResult login(HttpServletRequest request,HttpServletResponse response,
                                          @RequestParam(value="userName",required = false) String userName,
                                          @RequestParam(value="password",required = false) String password,
                                          @RequestParam(value="remember",required = false) String remember){
        JsonResult jsonResult = null;
        String ip = IPUtil.getLocalIp(request);
        System.out.println("登陆ip："+ip);
        if(StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(remember)){
            try {
                password = MD5Util.getMD5(DESUtil.decryption(password, GeneralConstants.DES_DECODE_KEY));
                String token = webUserService.login(request,userName,password,ip);
                //String token=ip;
                if(StringUtils.isNotEmpty(token)){
                    //登陆验证成功，判断是否自动登录
                    if(remember.equals("1")){
                        CookieUtil.setCookie(response,"token",token);
                    }else {
                        CookieUtil.setCookieDefault(response,"token",token);
                    }
                    //跳转主界面
                    jsonResult = new JsonResult(false,ErrorConstants.SERVER_SUCCESS,"/user/success");
                    //request.getRequestDispatcher("/user/success").forward(request, response);
                }else{
                    //验证失败
                    jsonResult = new JsonResult(false, ErrorConstants.LOGIN_ERROR, "用户名或密码错误");
                }
            } catch (Exception e) {
                jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
            }
        }
        return jsonResult;
    }*/
    /**
     * 测试登陆成功界面
     */
    @RequestMapping("/success")
    public String toSuccess() {
        return "/success";
    }
    /**
     * 退出登陆
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request,HttpServletResponse response){
        String token = CookieUtil.getCookie(request, "token").getValue();
        //清除session
        request.getSession().invalidate();
        //删除浏览器cookie
        Cookie cookie = CookieUtil.getCookie(request, "token");
        CookieUtil.removeCookie(response,cookie);
        return "/toLogin";
    }

    /**
     * 测试封装浏览器端传递过来的json格式的数据
     * @param request
     * @param response
     * @param jsonData json格式数据
     * @return
     */
    @RequestMapping("/testBuildListJson")
    public String testBuildListJson(HttpServletRequest request , HttpServletResponse response , String jsonData ){
        System.out.println("客户端传递过来的json格式的数据"+jsonData);
        //解析json格式的数据
        List<UserVO> userVOS = JSONObject.parseArray(jsonData, UserVO.class);

        System.out.println("集合长度"+userVOS.size());
        return "/toLogin";
    }

}
